package com.haisen.service.impl;

import com.haisen.core.utils.Constants;
import com.haisen.dataobject.dto.ItemCatDto;
import com.haisen.dataobject.dto.ItemDto;
import com.haisen.dataobject.dto.TreeDto;
import com.haisen.dataobject.entity.ItemCat;
import com.haisen.dataobject.entity.ItemParamGroup;
import com.haisen.dataobject.entity.ItemParamKey;
import com.haisen.dataobject.mapper.base.ItemCatMapper;
import com.haisen.dataobject.mapper.base.ItemParamGroupMapper;
import com.haisen.service.ItemCatService;
import com.haisen.service.ItemParamGroupService;
import com.sun.tools.javac.comp.Todo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ItemCatServcieImpl implements ItemCatService {

    @Autowired
    private ItemCatMapper itemCatMapper;

    @Autowired
    private ItemParamGroupMapper itemParamGroupMapper;
    @Autowired
    private ItemParamGroupService itemParamGroupService;

    @Override
    @Transactional
    public void create(ItemCat itemCat) {
        ItemCat parent = findOneById(itemCat.getParentId());
        itemCat.setUp(1);
        itemCatMapper.insertSelective(itemCat);
    }

    @Override
    @Transactional
    public void update(ItemCat itemCat) {
       itemCatMapper.updateByPrimaryKeySelective(itemCat);
    }

    @Override
    @Transactional
    public void delete(Long itemCatId) {
       itemCatMapper.deleteByPrimaryKey(itemCatId);
    }

    /**
     * 在页面上传递的itemCatId，所以returnd不为空
     * @param itemCatId
     * @return
     */
    @Override
    public ItemCat findOneById(Long itemCatId) {
        return itemCatMapper.selectByPrimaryKey(itemCatId);
    }

    @Override
    public List<ItemCatDto> findItemCatDto(Weekend example) {
        List<ItemCatDto> itemCatDtoList = new ArrayList<>();
        List<ItemParamGroup> itemParamGroupList = itemParamGroupMapper.selectAll();
        itemCatMapper.selectByExample(example)
                .forEach(o -> {
                    ItemCatDto itemCatDto = new ItemCatDto(o);
                    itemCatDto.setGroupnames(getGroupName(itemParamGroupList,o));
                    itemCatDtoList.add(itemCatDto);
                });

        return itemCatDtoList;
    }

    @Override
    public List<TreeDto> findItemCatTree(Long pId) {
         if (StringUtils.isEmpty(pId)){
             pId= Constants.ORG_ROOT_ID;
         }
        List<TreeDto> tds = new ArrayList<>();
        Weekend example = Weekend.of(ItemCat.class);
        WeekendCriteria<ItemCat, Object> criteria = example.weekendCriteria();
        criteria.andEqualTo(ItemCat::getParentId, pId);
        itemCatMapper.selectByExample(example).forEach(o -> tds.add(new TreeDto(o.getId(), o.getParentId(),o.getName(), Boolean.FALSE.equals(o.getLeaf()), o)));
        return tds;
    }

    @Override
    public List<ItemCat> findAll() {
        return itemCatMapper.selectAll();
    }

    @Override
    public List<ItemCat> findAllWithExclude(ItemCat excludeItemCat) {
        Weekend weekend = Weekend.of(ItemCat.class);
        WeekendCriteria<ItemCat, Object> criteria = weekend.weekendCriteria();
        // where id <> ''id and id not lik 'selfAsParentIds%'
        criteria.andNotEqualTo(ItemCat::getId, excludeItemCat.getId()).andNotLike(ItemCat::getParentIds, excludeItemCat.makeSelfAsParentIds() + "%");
        return itemCatMapper.selectByExample(weekend);
    }

    @Override
    public void move(ItemCat source, ItemCat target) {
        itemCatMapper.updateByPrimaryKeySelective(target);
        itemCatMapper.updateSalefParentIds(source.makeSelfAsParentIds());
    }

    /**
     * 查询数据列表中
     * @param itemParamGroupList--所有的grouplist
     * @param itemCat
     * @return
     */
    private String getGroupName(List<ItemParamGroup> itemParamGroupList,ItemCat itemCat){

          StringBuilder s = new StringBuilder();
            itemParamGroupList.stream()
                    .filter(o -> {
                        if (itemCat.getParmGroupIdList().contains(o.getId())) return true;
                        else return false;
                    }).map(m ->{
             return s.append(m.getGroupName()+",");
            }).collect(Collectors.toSet());

            if (s.length()>0){
                s.deleteCharAt(s.length()-1);
            }
        return s.toString();
    }

    @Override
    public List<ItemParamGroup> selectGroups(Long id) {
        return itemCatMapper.selectGroups(id).getParmGroupIdList();
    }

    @Override
    public List<ItemCatDto> selectCatAndGroups() {
         List<ItemCat> itemCatList = itemCatMapper.selectAll();
        List<ItemCatDto> itemCatDtoList = new ArrayList<>();

        itemCatList.forEach( o ->{
            ItemCatDto itemCatDto = new ItemCatDto();
            BeanUtils.copyProperties(o,itemCatDto);
            //非数字不能转换为id
           List<Long> groupids= Arrays.asList(o.getParamGroupIds().split(",")).stream()
                   .filter( e -> {
                       if(!StringUtils.isEmpty(e)) return true;
                       else return false;
                   })
                    .map(e -> {
                        return Long.valueOf(e);
                    }).collect(Collectors.toList());
            itemCatDto.setParmGroupIdList(itemParamGroupService.findGroups(groupids));
            itemCatDtoList.add(itemCatDto);
        });
       //直接map关联对象语句没调试好，cat包含grouplist，暂采用上面处理方式
       // return itemCatMapper.selectCatAndGroups();
        return itemCatDtoList;
    }

    @Override
    public List<ItemParamKey> selectParamKeys(Long id) {
        return itemCatMapper.selectParamKeys(id);
    }



}
